package pc

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"errors"
	"net/url"
	"strconv"
	"strings"
)
func unescape(str string) (rs string, err error) {
	str = strings.Replace(str, "%u", "\\u", -1)
	if str, err = url.PathUnescape(str); err != nil {
		return
	}

	rs, err = strconv.Unquote("\"" + str + "\"")
	return
}
func UnescapeJsEscape(str string) (rs string, err error) {
	idx := 0
	var chr, chr0 byte
	l := len(str)
	buf := bytes.NewBuffer(make([]byte, 0, l))
	for {
		chr = str[idx]
		if chr == '%' {
			if idx+2 >= l {
				err = errors.New("错误的结构")
				return
			} else {
				chr0 = str[idx+1]
				if chr0 == 'u' || chr0 == 'U' {
					//四字节
					if idx+5 >= l {
						err = errors.New("错误的结构")
						return
					} else {
						if v, err := hex.DecodeString(str[idx+2:idx+6]); err != nil {
							return "", err
						} else {
							//buf.WriteString(string(binary.BigEndian.Uint16(v)))
							buf.WriteRune(rune(binary.BigEndian.Uint16(v)))
							idx += 6
						}
					}
				} else {
					//两个字节
					if v, err := hex.DecodeString(str[idx+1:idx+3]); err != nil {
						return "", err
					} else {
						buf.Write(v)
						idx += 6
					}
					idx += 3
				}
			}
		} else {
			//一般字符
			buf.WriteByte(chr)
			idx++
		}
		if idx >= l {
			break
		}
	}
	rs = string(buf.Bytes())
	return
}